import router from './router';
import {RouteLocationNormalized} from 'vue-router';
import { ElMessage } from 'element-plus';
import NProgress from "nprogress";
import 'nprogress/nprogress.css';
import {useAuthStore} from './store/modules/auth'; //个人定义的文件
import {usepermissionStore} from './store/modules/permission'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login']


router.beforeEach(async(to:RouteLocationNormalized, _:RouteLocationNormalized,next:any)=>{
    //进度条
    NProgress.start()
    const authStore = useAuthStore()
    if(authStore.token){
        if(to.path === '/login'){
            console.log("token拿到了")
            next({path:'/'})
            NProgress.done()
        }else{
            // 
            //所以在刷新页面时需要判断一下router对象是否执行了添加新路由的操作
            const permissionStore =usepermissionStore()
            if(permissionStore.addRouteState){
                // console.log("permissionStore.addRouteState",permissionStore.addRouteState);
                next();
            }else{
                try {     
                    permissionStore.generateRoutes()
                    // console.log("permissionStore.dynamicRoutes",permissionStore.dynamicRoutes)
                    permissionStore.dynamicRoutes.forEach(route => {
                        router.addRoute(route)   
                    })
                } catch (error) {
                    console.log("路由信息加载失败！！！");
                    ElMessage.error("路由信息加载失败！！！")
                    next('/login')
                    NProgress.done()
                }
                permissionStore.SetAddRoutesState(true);
                next({ ...to, replace: true })
            }
            NProgress.done()   
        }
    }else{
        console.log("token没拿到")
        if(whiteList.indexOf(to.path) !== -1){
            next()
        }else{
            next({path:'/login'})
        }
        NProgress.done()
    }
})
